package com.tckdq.tcc.web.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tckdq.tcc.exception.GlobalException;
import com.tckdq.tcc.service.IBlacklistService;
import com.tckdq.tcc.domain.Blacklist;
import com.tckdq.tcc.query.BlacklistQuery;
import com.tckdq.tcc.result.JsonResult;
import com.tckdq.tcc.result.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Wrapper;

@RestController
@RequestMapping("/blacklist")
public class BlacklistController {

    @Autowired
    public IBlacklistService blacklistService;

    @RequestMapping(value="/saveBlackList",method= RequestMethod.POST)
    public JsonResult saveBlackList(@RequestBody Blacklist blacklist){
        if (StringUtils.isEmpty(blacklist.getPhone())) {
            throw new GlobalException("手机号不能为空",null);
        }
        blacklistService.saveBlackList(blacklist);
        return JsonResult.success();
    }



    /**
    * 保存和修改公用的
    */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public JsonResult saveOrUpdate(@RequestBody Blacklist blacklist){

        if(blacklist.getId()!=null){
            EntityWrapper<Blacklist> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("reason",blacklist.getReason());
            blacklistService.update(blacklist,entityWrapper);
        }else{
            blacklistService.insert(blacklist);
        }
        return JsonResult.success();
    }

    /**
    * 删除对象
    */
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public JsonResult delete(@PathVariable("id") Long id){
        EntityWrapper<Blacklist> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("id",id);
        blacklistService.delete(entityWrapper);
        return JsonResult.success();
    }

    /**
   * 获取对象
   */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.success(blacklistService.selectById(id));
    }


    /**
    * 查询所有对象
    */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public JsonResult list(){
        return JsonResult.success(blacklistService.selectList(null));
    }


    /**
    * 带条件分页查询数据
    */
    @RequestMapping(value = "/pagelist",method = RequestMethod.POST)
    public JsonResult page(@RequestBody BlacklistQuery query){
        Page<Blacklist> page = new Page<Blacklist>(query.getPage(),query.getRows());
        page = blacklistService.selectPage(page);
        return JsonResult.success(new PageList<Blacklist>(page.getTotal(),page.getRecords()));
    }
}
